 ///
 /// @file    CopyControl.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-05-03 11:12:21
 ///
 
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;

class Base
{
public:
	Base()
	: _data(new char[1]())
	{	cout << "Base()" << endl;	}

	Base(const char * data)
	: _data(new char[strlen(data) + 1]())
	{
		strcpy(_data, data);
		cout << "Base(const char *)" << endl;
	}

	Base(const Base & rhs)
	: _data(new char[strlen(rhs._data) + 1]())
	{
		strcpy(_data, rhs._data);
		cout << "Base(const Base & )" << endl;
	}

	Base & operator=(const Base & rhs)
	{
		cout << "Base & operator=(const Base &)" << endl;
		if(this != &rhs) {
			delete [] _data;

			_data = new char[strlen(rhs._data) + 1]();
			strcpy(_data, rhs._data);
		}
		return *this;
	}


	~Base()
	{
		cout << "~Base()" << endl;
		if(_data) {
			delete [] _data;
			_data = nullptr;
		}
	}

	friend ostream & operator<<(ostream & os, const Base & rhs);
private:
	char * _data;
};

ostream & operator<<(ostream & os, const Base & rhs)
{
	os << rhs._data;
	return os;
}

class Derived
: public Base
{
public:
	Derived(const char * data)
	: Base(data)
	{	cout << "Derived()" << endl;	}

};
 
void test0() 
{
	Derived d1("hello");
	cout << "d1:" << d1 << endl;
	Derived d2 = d1;//拷贝构造函数
	cout << "d2:" << d2 << endl;

	Derived d3("world");
	cout << "d3:" << d3 << endl;
 
	cout << "\n执行赋值操作:" << endl;
	d3 = d1;//赋值运算符函数
	cout << "d3:" << d3 << endl;
} 
 
int main(void)
{
	test0();
	return 0;
}

















